package cn.hyy.FVOnline.controller;

import cn.hyy.FVOnline.entity.Address;
import cn.hyy.FVOnline.service.AddressService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/address")
public class AddressComtroller {

    @Autowired
    private AddressService addressService;


    @RequestMapping(value = "/findMyAddress", produces = "text/html;charset=UTF-8;")
    public @ResponseBody String findMyAddress(@RequestParam("userId")String userId){

        List<Address> address = addressService.findMyAddress(Integer.parseInt(userId));

        return JSON.toJSONString(address);
    }


    @RequestMapping(value = "/loadAddress", produces = "text/html;charset=UTF-8;")
    public @ResponseBody String loadAddress(){

        JSONObject jo = addressService.findToLoadAddress();

        return jo.toJSONString();
    }

    @RequestMapping(value = "/delAddress", produces = "text/html;charset=UTF-8;")
    public @ResponseBody String delAddress(@RequestParam("id")String id){

        JSONObject jo = new JSONObject();
        try {
            addressService.delAddress(Integer.parseInt(id));
            jo.put("code","success");
            jo.put("message","删除收货地址成功");
        }catch (Exception e){
            jo.put("code","error");
            jo.put("message","删除收货地址失败");
        }
        return jo.toJSONString();
    }


    @RequestMapping(value = "/addAddress", produces = "text/html;charset=UTF-8;")
    public @ResponseBody String addAddress(@RequestParam("receive")String receive,@RequestParam("telephone")String telephone,@RequestParam("province")String province,@RequestParam("city")String city,@RequestParam("details")String details,@RequestParam("userId")String userId){

        JSONObject jo = new JSONObject();
        try {
            Address address = new Address();
            address.setReceiveName(receive);
            address.setTelephone(telephone);
            address.setProvince(province);
            address.setCity(city);
            address.setDetails(details);
            address.setUid(Integer.parseInt(userId));
            addressService.addAddress(address);
            jo.put("code","success");
            jo.put("message","添加收货地址成功");
        }catch (Exception e){
            jo.put("code","error");
            jo.put("message","添加收货地址失败");
        }
        return jo.toJSONString();
    }

}
